<template>
  <div style="background:white;margin-top:10px;border-radius:10px;height:270px;">
    <el-row>
      <div>
        <el-col :span="24">
          <div class="projectIndexTitle">
            <div class="projectIndexSquare"></div>
            <span class="projectIndexInfo">超期任务：</span>
            <el-radio-group v-model="redioGroup" :max="1" size="mini" @change="tabclik">
              <el-radio-button class="indexRadioButton" label="threeDays">三天内</el-radio-button>
              <el-radio-button class="indexRadioButton" label="oneWeek">一周内</el-radio-button>
            </el-radio-group>
          <el-button class="filter-item" v-if="ifMarketManger" type="primary" size="mini" icon="el-icon-download" @click="doExportExcel">导出</el-button>
          </div>
          <!-- <el-tabs style="height:40px;margin-left:10px" @tab-click="tabclik" value="threeDays">
            <el-tab-pane label="3天内超期任务" name="threeDays"></el-tab-pane>
            <el-tab-pane label="一周内超期任务" name="oneWeek"></el-tab-pane>
          </el-tabs> -->
        </el-col>
        <!-- <el-col :span="7" :offset="2">
          <el-select placeholder="请选择" v-model="projectOrMilepost">
            <el-option v-for=" item in selections" :label="item.label" :value="item.value" :key="item.value">
            </el-option>
          </el-select>
        </el-col> -->
        <!-- <el-col :span="4" :offset="1">
          <el-button type="primary" size="small" style="margin-top:3px">导出</el-button>
        </el-col> -->
      </div>
    </el-row>
    <!-- <el-row>
      <div style="height:1rem"></div>
    </el-row> -->
    <el-row style="padding:4px 20px 0 20px">
      <el-table class="tl-table" ref="mainTable" height="210" :resizable-refs="['search', 'toolbar', 'selector', 'pager']" :data="datas" row-key="id" @row-click="clicktaskrow" border fit v-loading="tableLoading">
        <!-- <el-table-column type="selection" min-width="25%"></el-table-column> -->
        <el-table-column v-if="ifMarketManger" prop="deptname" label="部门" min-width="20%" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column prop="projectname" label="项目名称" min-width="20%" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column prop="taskname" label="任务名称" min-width="20%" :show-overflow-tooltip="true" align="left"></el-table-column>
        <el-table-column prop="responsible" label="负责人" min-width="20%" :show-overflow-tooltip="true" align="center"></el-table-column>
        <el-table-column prop="planenddate" label="计划完成日期" min-width="20%" :show-overflow-tooltip="true" align="center">
          <template slot-scope="scope">{{ scope.row.planenddate | toDateTime('yyyy-MM-dd') }}</template>
        </el-table-column>
      </el-table>
    </el-row>
    <tl-edit ref="editForm"></tl-edit>
    <tl-start-TaskEdit ref="startTaskEdit" @refresh="doRefresh"></tl-start-TaskEdit>
    <tl-edit-Feedback ref="editFeedback" @refresh="doRefresh"></tl-edit-Feedback>
  </div>
</template>

<script>
import { getAction } from '@tapui/utils/http'
import { validateNull } from '@tapui/utils/validate'
import { mixin_list } from '@tapui/mixins/mixin_list'
import tlEdit from '@/views/mpm/mpmProjectTask/edit'
import { MPM_TASK_STATE } from '@/const/const'
import { exportExcel, exportExcelAxio } from '@tapui/api/office'
import tlStartTaskEdit from '@/views/mpm/mpmProjectTaskFeedback/startTaskEdit'
import tlEditFeedback from '@/views/mpm/mpmProjectTaskFeedback/edit'
// 即将超期的任务
const baseUrl = process.env.BASE_API
export default {
  name: 'taskSoonOverdue',
  mixins: [mixin_list],
  components: { tlEdit, tlStartTaskEdit, tlEditFeedback },
  data() {
    return {
      timeColName: 'oneWeek',
      projectOrMilepost: '',
      datas: [],
      dateValue: new Date(),
      mySelection: '',
      dataPermissionFlagForRecentlyProject: 'org',
      tableLoading: false,
      redioGroup: 'threeDays',
      isQueryOnCreated: false,
      urlPrefix: '/mpm/mpmIndex/',
      url: {
        querySoonOverdueTask: '/mpm/mpmIndex/querySoonOverdueTask'
      },
      // 判断是否是经营管理部人员
      ifMarketManger: false
    }
  },
  computed: {},
  methods: {
    // 点击打开任务详情页,如果是任务的责任人，直接打开任务反馈页
    clicktaskrow(row, column, event) {
      if (this.$store.getters.user.code === row.responsiblecode && row.taskstate === MPM_TASK_STATE.notStart) {
          this.starTaskDialog('startTaskEdit', row)
        } else if (this.$store.getters.user.code === row.responsiblecode && row.taskstate === MPM_TASK_STATE.inComplete) {
          this.openFeedbackDialog('editFeedback', row)
        } else {
          this.$refs.editForm.projectcode = row.projectcode
          let id = row.id
          this.openviewform('editForm', id)
        }
    },
    /** 打开编辑对话框 */
    openviewform(editForm, id) {
      this.$refs[editForm].id = id
      this.$refs[editForm].isAdd = false
      this.$refs[editForm].visible = true
      this.$refs[editForm].disableEditSubmit = true
    },
    // /** 刷新,页号不变*/
    doRefresh() {
      this.loadData({})
    },
    tabclik() {
      this.loadData({})
    },
    loadData(param) {
      // loading 加载
      this.tableLoading = true
      // 如果切换首页的一级tab栏调用loadData接口，将dataPermission赋给超期任务模块
      if (!validateNull(param.dataPermissionFlag)) {
        this.dataPermissionFlagForRecentlyProject = param.dataPermissionFlag
      }
      var paramDefault = {
        dataPermissionFlag: this.dataPermissionFlagForRecentlyProject,
        overdueDays: this.redioGroup === 'threeDays' ? 3 : 7,
        pageSize: 2000,
        sidx: 'PLANENDDATE',
        sord: 'asc'
      }
      getAction(this.url.querySoonOverdueTask, paramDefault).then((res) => {
        if (res.success) {
          this.datas = res.result
          // 重载数据，防止表格高度变矮（element自带的BUG）
          this.$nextTick(() => {
            this.$refs.mainTable.doLayout()
          })
        } else {
          this.$tap.alert(res.message, 'warning')
        }
        this.tableLoading = false
      })
    },
    /** 开始任务 */
    starTaskDialog(editForm, rowData) {
      this.$refs[editForm].visible = true
      this.$refs[editForm].taskid = rowData.id
      if (rowData.taskstate !== '0') {
        this.$tap.alert('任务不是未开始状态，无法开始！', 'warning')
        return
      }
    },
    // 打开任务反馈页面
    openFeedbackDialog(editForm, rowData) {
      const params = {
        taskid: rowData.id
      }
      getAction('/mpm/projectTask/queryTaskFeedbackList', params).then((res) => {
        if (res.success) {
          if (res.result && res.result.length > 0) {
            if (res.result[0].state === 1) {
              this.openViewDialog(editForm, res.result[0].id)
            } else if (res.result[0].state === 0 || res.result[0].state === 2) {
              this.openEditDialog(editForm, res.result[0].id)
            } else {
              this.openAddFeedbackDialog(editForm, rowData)
            }
          } else {
            this.openAddFeedbackDialog(editForm, rowData)
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
     /** 导出Excel*/
     doExportExcel() {
      if (!this.beforeExportData()) return
      let cols = []
      this.$refs.mainTable.$children.forEach((col) => {
        if (col.$options._componentTag === 'el-table-column') {
          if (col.$options.propsData.prop) {
            cols.push(col.$options.propsData.prop + ';' + col.$options.propsData.label)
          }
        }
      })
      // 加上超期类型字段
      cols.push("datetype;超期类型")
      let url = baseUrl + `${this.url.exportExcel}`
      let data = {}
      Object.assign(data, this.getQueryParams(), { cols: cols.join(',') })
      exportExcelAxio({ url: url, data: data })
        .then((res) => {
          var reader = new FileReader()
          reader.readAsText(res.data, 'utf-8')
          reader.onload = () => {
            try {
              var info = JSON.parse(reader.result)
              this.$tap.alert(info.message)
            } catch (e) {
              var isTaskExport = res.headers.istaskexport
              if (isTaskExport === '1') {
                this.$tap.alert('系统正在导出，请到excel导出任务页面下载')
              } else {
                var blob = new Blob([res.data], { type: 'application/octet-stream;charset=utf-8' })
                var filename = decodeURI(res.headers['filename'])
                if (typeof filename === 'undefined') {
                  filename = '导出数据.xlsx'
                }
                var tempObjectUrl = window.URL.createObjectURL(blob)
                var aLink = document.createElement('a')
                aLink.style.display = 'none'
                aLink.download = filename
                aLink.href = tempObjectUrl
                document.body.appendChild(aLink)
                aLink.click()
                document.body.removeChild(aLink)
                window.URL.revokeObjectURL(tempObjectUrl)
                this.afterExportData()
              }
            }
          }
        })
        .catch((error) => {
          this.$tap.alert(error, 'warning')
        })
    },
    /** 打开新增对话框实现 */
    openAddFeedbackDialog(editForm, rowData) {
      this.$refs[editForm].taskInfo = rowData
      this.$refs[editForm].isAdd = true
      this.$refs[editForm].visible = true
      this.$refs[editForm].disableEditSubmit = false
    }
  },
  created() {
    this.ifMarketManger = false
    // 判断当前用户是否是经营管理部人员
    if (this.$store.getters.roles) {
      for (let role of this.$store.getters.roles) {
        this.ifMarketManger = role === 'businessManager' ? true : this.ifMarketManger
      }
    }
  },
  activated() {
    this.$refs.mainTable.doLayout()
  }
}
</script>

<style lang="scss" scoped>

//修改表格的滚动条
/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 17px!important;
}
.filter-item {
  margin-left: 10px;
}
.parentCenter {
  display: flex;

  /* background: #cecece; */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}
.el-pagination__total {
  margin: 0px;
}
.pagebar {
  font-size: 14px;
}
.child {
  background: #000;
  width: 10%;
  height: 10%;
}
/** 表格上边、左边的线 */
.el-table--border,
.el-table--group {
  border: none;
}
/**  表格下边的线 */
.el-table--border::before,
.el-table--group::before {
  width: 0;
}
/**  表格右边的线 */
.el-table--border::after,
.el-table--group::after {
  height: 0;
}
/** 表格样式相关 */
.tl-table {
  /** “暂无数据”居中显示 */
  /deep/ .el-table__empty-block {
    justify-content: center;
    align-items: center;
    padding: 0;
  }
  /deep/ .el-table__empty-text {
    text-align: center;
  }
  // 滚动条的宽度
  /deep/ .el-table__body-wrapper::-webkit-scrollbar {
    width: 10px; // 横向滚动条
    height: 7px; // 纵向滚动条 必写
  }
  // 滚动条的滑块
  /deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
    border-radius: 3px;
    background-color: rgba(144, 147, 153, 0.3);
  }
  // 控制边框
  /deep/ .gutter {
    display: none !important;
  }
  /deep/ .el-table__header-wrapper .el-table__header {
    table-layout: auto !important;
  }
  /deep/ .el-table__body-wrapper .el-table__body {
    table-layout: auto !important;
  }
}
</style>
